<template>
  <div style="width:100%;height:100%">
    <div class="head" style="height:50px;display:flex;align-items:center;">
     <!--  <span class="title">工作安排</span>
      <span class="unfinish">（未完成：{{unFinishCount}}项）</span> -->
      <div class="date-info">
        <div style="width:100%;height:100%;display:flex;align-items:center;justify-content: center">
          <i class="iconfont iconyoubiao date-infoicon" @click="prev"></i>
          <span>{{dateRangeInfo}}</span>
          <i class="iconfont iconzuobiao date-infoicon" @click="next"></i>
        </div>
      </div>
      <div class="date-tools">
        <div class="tools-today" @click="toToday()">
          今天
        </div>
        <div class="tools-switch">
          <el-radio-group v-model="switchDate" size="small">
            <el-radio-button label="周"></el-radio-button>
            <el-radio-button label="月"></el-radio-button>
          </el-radio-group>
        </div>
      </div>
    </div>
    <div class="contain work-plan-contain">
      <!-- <div class="work-plan-left">
        <div class="calendar">
          <div class="calendar-head">
            <i class="el-icon-arrow-left" @click="addMonth(-1)"></i>
            <span>{{leftCurrMonth}}</span>
            <i class="el-icon-arrow-right" @click="addMonth(1)"></i>
          </div>
          <div class="calendar-body">
            <div class="calendar-xingqi">
              一
            </div>
            <div class="calendar-xingqi">
              二
            </div>
            <div class="calendar-xingqi">
              三
            </div>
            <div class="calendar-xingqi">
              四
            </div>
            <div class="calendar-xingqi">
              五
            </div>
            <div class="calendar-xingqi">
              六
            </div>
            <div class="calendar-xingqi">
              日
            </div>
            <div @click="calendarClick(item)" :class="['calendar-date',{'gary': item.gary,'today': item.value == today,'active':item.value == leftActiveDay}]" v-for="(item,index) in dateList" :key="index">
              {{item.label}}
            </div>
          </div>
        </div>
        <div class="remark">
          <div>注：</div>
          <div class="line"></div>
          <div class="legend-item">
            <span class="square" style="background-color:#CCCCCC"></span>
            <span>未派工</span>
          </div>
          <div class="legend-item">
            <span class="square" style="background-color:#FFB052"></span>
            <span>待执行</span>
          </div>
          <div class="legend-item">
            <span class="square" style="background-color:#3C98F5"></span>
            <span>执行中</span>
          </div>
          <div class="legend-item">
            <span class="square" style="background-color:#10C8E6"></span>
            <span>待确认</span>
          </div>
          <div class="legend-item">
            <span class="square" style="background-color:#38CE4D"></span>
            <span>已完成</span>
          </div>
          <div class="description">
            (已完成按实际时间显示,未完成按计划时间显示。粗体表示需要停电的计划。）
          </div>
        </div>
      </div> -->
      <div class="work-plan-right">
        <div class="work-plan-search">
        </div>
        <div class="work-plan-contain">
          <!-- <div class="work-plan-item" v-for="(item,index) in workPlanList" :key="index" @click="openDetail(item)"
          :style="{width:item.width,backgroundColor:item.color,marginTop:item.top,marginLeft:item.left}">
            <el-tooltip placement="top">
              <div slot="content" style="font-size: 14px">
                计划开始时间：{{item.workBeginDate}}
                <br/>
                计划结束时间：{{item.workEndDate}}
                <br/>
                负责人：{{item.workMasterUserName}}
                <br/>
                工作成员：{{item.workMemberUserNames}}
                <br/>
                工作班组：{{item.workTeamName}}
                <br/>
                工作内容：{{item.workContent}}
                <br/>
                工单来源：{{$store.getters["fineDirtDataName"]("order_from",item.dataFrom)}}
                <br/>
                设备管理单位：{{item.workTeamName}}
                <br/>
              </div>
              <div style="color: #fff;overflow: hidden;white-space: nowrap;text-overflow: ellipsis;">
                <i v-if="item.workMasterUserName == userInfo.userName" class="el-icon-user-solid"></i>
                {{item.workContent}}
              </div>
            </el-tooltip>
          </div> -->
          <table>
            <tr>
              <th :class="[{'active': item.value === leftActiveDay}]" v-for="(item,index) in thList" :key="index">{{item.label}}</th>
            </tr>
            <tr>
              <td :class="[{'active': item.value === leftActiveDay}]" v-for="(item,index) in thList" :key="index"></td>
            </tr>
          </table>
        </div>
      </div>
    </div>
    <dialogPublic
      :title="'信息选择'"
      height="460px"
      :show.sync="showMember"
      @doSubmit="addSeleteMember"
      :appendTobody="true"
      @doClose="() => (showMember = false)"
    >
      <orgMemberSelect
        ref="orgMemberSelect"
        :partTreeData="true"
        v-if="showMember"
        :seleteSetting="orgMemberSelect"
      ></orgMemberSelect>
    </dialogPublic>
  </div>
</template>
<script>
export default {
  props: {
    isTeam: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      switchDate: '周',// 周，月切换
      orgMemberSelect: {},
      dateRangeInfo: '',
      unFinishCount: 0,
      showMember: false,
      today: this.elementDate.getCurrentDate(), //今天
      leftActiveDay: this.elementDate.getCurrentDate(),// 左边日历选中的日期
      leftCurrMonth: this.elementDate.getCurrentMonth(),// 左边日历当前月份
      rightStartDay: this.elementDate.getCurrentDate(),// 右边日历开始日期
      rightCurrMonth: this.elementDate.getCurrentMonth(),// 右边日历当前月份
      dateList: [], // 左边日历日期列表
      thList: [], // 右边日历表头
      workPlanList: [],
      searchFrom: {
        line: '',
      },
      userInfo: this.$store.getters.userInfo
    }
  },
  created() {
    this.buildDateList()
    this.buildThList()
    this.getWorkPlanList()
    this.getUnFinishCount()
  },
  methods: {
    jumpRouter(row) {

    },
    getUnFinishCount() {
      unFinishListApi({page:0,pageCount:0}).then(res => {
        this.unFinishCount =  res.data.total
      })
    },
    openDetail(row) {
      let id = row.id
      let workState = row.workState
      let workCode = row.workCode
      let path = workState === '1' ? '/orderWeave/dailyOrderWeave' : '/orderExecute'
      const { href } = this.$router.resolve({
        path: path,
      })
      window.open(`${href}?id=${id}&workState=${workState}&workCode=${workCode}`, "_blank")
    },
    inputOnInput(e) {
      this.$forceUpdate()
    },
    async getWorkPlanList() {
      let params = {
        planDateStart: this.thList[0].value + ' 00:00:00',
        planDateEnd: this.thList[this.thList.length - 1].value + ' 23:59:59',
        page: 1,
        pageCount: 1000,
        workState: this.searchFrom.workState,
        workType: this.searchFrom.workType,
        workClassify: this.searchFrom.workClassify,
        working: this.searchFrom.working,
        workMemberUserIds: this.searchFrom.workMemberUserIds
      }
      let res
      if (this.isTeam) {
        res = await getTeamListApi(params)
      } else {
        res = await getListApi(params)
      }
      this.workPlanList = res.data.list
      this.dualWorkPlanList()
    },
    dualWorkPlanList() {
      let colorArr = {
        '1': '#CCCCCC',
        '2': '#CCCCCC',
        '3': '#FFB052',
        '4': '#3C98F5',
        '5': '#10C8E6',
        '6': '#38CE4D'
      }
      this.workPlanList.forEach((item,index) => {
        // 背景色
        item.color = colorArr[item.workState]
        let leftIndex = this.thList.findIndex(th => {
          return th.value === item.workBeginDate.split(' ')[0]
        })
        // 左边距
        item.left = `calc(100% / ${this.thList.length} * ${leftIndex})`
        item.top = this.getTop1(item,index)
        let days = this.getDaysBetween(item.workBeginDate,item.workEndDate) + 1
        if (days > this.thList.length) {
          days = this.thList.length + 1
        }
        item.width = `calc(100% / ${this.thList.length} * ${days})`
      })
    },
    getTop1(item,index) {
      let count = 1
      let start1 = item.workBeginDate.split(' ')[0]
      let end1 = item.workEndDate.split(' ')[0]
      if (index ===0) {
        item.rowIndex = count
        return 37*count +'px'
      }
      let filterList = this.workPlanList.filter(item1 => {
        let start2 = item1.workBeginDate.split(' ')[0]
        let end2 = item1.workEndDate.split(' ')[0]
        return this.isDateIntersection(start1,end1,start2,end2) && item1.rowIndex
      })
      if (!filterList.length) {
        item.rowIndex = count
        return 37*count +'px'
      } else {
        count = filterList[filterList.length - 1].rowIndex + 1
        item.rowIndex = count
        return 37*count +'px'
      }
    },
    // 获取上边距
    getTop(item,index) {
      let count = 1
      let maxIndex = 1
      let start1 = item.workBeginDate.split(' ')[0]
      let end1 = item.workEndDate.split(' ')[0]
      this.workPlanList.forEach((item1, index1) => {
        if (index1 < index) {
          let start2 = item1.workBeginDate.split(' ')[0]
          let end2 = item1.workEndDate.split(' ')[0]
          if (maxIndex < item1.rowIndex) {
            maxIndex = item1.rowIndex
          }
          if (this.isDateIntersection(start1,end1,start2,end2)) {
            count = count+1
          }
        }
      })
      if (index != 0 && count > maxIndex + 1) {
        count = maxIndex + 1
      }
      item.rowIndex = count
      return 37*count +'px'
    },
    // 判断两个日期区间是否重合
    isDateIntersection(start1, end1, start2, end2) {
      var startdate1 = new Date(start1.replace("-", "/").replace("-", "/"));
      var enddate1 = new Date(end1.replace("-", "/").replace("-", "/"));
      var startdate2 = new Date(start2.replace("-", "/").replace("-", "/"));
      var enddate2 = new Date(end2.replace("-", "/").replace("-", "/"));
      if (startdate1 >= startdate2 && startdate1 <= enddate2) {
        return true
      }
      if (enddate1 >= startdate2 && enddate1 <= enddate2) {
        return true
      }
      if (startdate1 <= startdate2 && enddate1 >= enddate2) {
          return true
      }
      return false
    },
    // 获取两个日期之间相差的天数
    getDaysBetween(s1,s2) {
      var startDate = new Date(s1.split(' ')[0])
      var endDate = new Date(s2.split(' ')[0])
      var days = (endDate - startDate)/(1*24*60*60*1000)
      return days
    },
    // 清空选人框
    clear() {
      this.searchFrom.workMemberUserIds = ''
      this.searchFrom.workMemberUserNames = ''
    },
    toToday() {
      this.leftActiveDay = this.today
      this.rightStartDay = this.today
      this.leftCurrMonth = this.elementDate.getCurrentMonth()
      this.rightCurrMonth = this.leftCurrMonth
      this.buildThList()
      this.buildDateList()
    },
    //确定选择
    addSeleteMember() {
      let data = this.$refs.orgMemberSelect.getSeleteData();
      let names = "";
      let ids = "";
      if (data) {
        names = data
          .map(i => {
            return i[this.orgMemberSelect.column[0].prop];
          })
          .join();
        ids = data
          .map(i => {
            return i.id;
          })
          .join();
      }
      this.searchFrom.workMemberUserIds = ids
      this.searchFrom.workMemberUserNames = names
      this.showMember = false
    },
    //选择组织人员
    goSeleteOrgMember(item, type) {
      this.currentItem = item;
      let value = this.searchFrom.workMemberUserNames || "";
      let ids = this.searchFrom.workMemberUserIds || "";
      let arr = value ? value.split(",") : [];
      let idsArr = ids ? ids.split(",") : [];
      let chosedData = [];
      
      //组织类型
      this.orgMemberSelect = {
        seleteType: 'user',
        radio: true,
        props: {
          label: "deptName",
          children: "children"
        },
        column: [
          {
            label: "用户名",
            prop: "userName",
            width: 60
          },
          {
            label: "电话",
            prop: "mobile",
            width: 100
          },
          {
            label: "部门",
            prop: "departmentName",
            width: 100
          }
        ],
        chosedData: []
      };

      arr.map((i, index) => {
        let obj = {}
        obj.id = idsArr[index]
        obj[this.orgMemberSelect.column[0].prop] = arr[index]
        chosedData.push(obj)
      })
      this.orgMemberSelect.chosedData = chosedData
      this.showMember = true
    },
    addMonth(n) {
      this.leftCurrMonth = this.elementDate.addMonth(this.leftCurrMonth,n)
      this.buildDateList()
    },
    calendarClick(row) {
      this.leftActiveDay = row.value
      this.rightStartDay = row.value
      this.rightCurrMonth = this.rightStartDay.split('-')[0] + '-' + this.rightStartDay.split('-')[1]
      this.buildThList()
    },
    prev() {
      if(this.switchDate == '周') {
        this.rightStartDay = this.elementDate.getNextDate(this.rightStartDay,-7)
        this.rightCurrMonth = this.rightStartDay.split('-')[0] + '-' + this.rightStartDay.split('-')[1]
      }else {
        this.rightCurrMonth = this.elementDate.addMonth(this.rightCurrMonth,-1)
        this.rightStartDay = this.rightCurrMonth + '-01'
      }
      this.buildThList()
    },
    next() {
      if(this.switchDate == '周') {
        this.rightStartDay = this.elementDate.getNextDate(this.rightStartDay,7)
        this.rightCurrMonth = this.rightStartDay.split('-')[0] + '-' + this.rightStartDay.split('-')[1]
      }else {
        this.rightCurrMonth = this.elementDate.addMonth(this.rightCurrMonth,1)
        this.rightStartDay = this.rightCurrMonth + '-01'
      }
      this.buildThList()
    },
    buildThList() {
      let tempList = []
      if (this.switchDate == '周') {
        let endDate = this.elementDate.getNextDate(this.rightStartDay,6)
        this.dateRangeInfo = parseInt(this.rightStartDay.split('-')[1]) + '月' + parseInt(this.rightStartDay.split('-')[2])
          + '日-' + parseInt(endDate.split('-')[1]) + '月' + parseInt(endDate.split('-')[2]) + '日'
        for(let i=0;i<=6;i++) {
          let day = this.elementDate.getNextDate(this.rightStartDay,i)
          let week = this.elementDate.getWeek(day)
          let str = day.split('-')[1] + '-' + day.split('-')[2] + ' ' + week
          tempList.push({
            label: str,
            value: day
          })
        }
      } else {
        this.dateRangeInfo = this.rightCurrMonth.split('-')[0] + '年' + this.rightCurrMonth.split('-')[1] + '月'
        let monthDays = this.elementDate.getMonthDays(this.rightCurrMonth) // 获取本月天数
        for(let i=1;i<=monthDays;i++) {
          tempList.push({
            label: i<10 ? '0'+i:i,
            value: this.rightCurrMonth + '-' + (i<10 ? '0'+i:i)
          })
        }
      }
      this.thList = tempList
    },
    buildDateList() {
      this.dateList = []
      let monthDays = this.elementDate.getMonthDays(this.leftCurrMonth) // 获取本月天数
      let firstDayWeek = this.elementDate.getMonthFirstDayWeek(this.leftCurrMonth) //第一天星期几
      let lastDayWeek = this.elementDate.getMonthLastDayWeek(this.leftCurrMonth) //最后一天星期几
      if(firstDayWeek != 1) {
        for(let i=firstDayWeek || 7;i>1;i--) {
          let date = this.elementDate.getNextDate(this.leftCurrMonth + '-01',1-i)
          this.dateList.push({
            label: parseInt(date.split('-')[2]),
            value: date,
            gary: true
          })
        }
      }
      for(let i=1;i<=monthDays;i++) {
        this.dateList.push({
          label: i,
          value: this.leftCurrMonth + '-' + (i<10?('0'+i):i),
          gary: false
        })
      }
      if (lastDayWeek!=0) {
        for(let i=0;i<=6-lastDayWeek;i++) {
          let date = this.elementDate.getNextDate(this.leftCurrMonth + '-'+monthDays,i+1)
          this.dateList.push({
            label: parseInt(date.split('-')[2]),
            value: date,
            gary: true
          })
        }
      }
    },
  },
  watch: {
    switchDate() {
      this.buildThList()
      this.dualWorkPlanList()
    },
    thList() {
      this.getWorkPlanList()
    }
  }
}
</script>
<style lang="less">
.date-info {
  width: calc(100% - 360px);
  text-align: center;
  display: inline-block;
  span {
    font-size: 16px;
    font-weight: bold;
    color: #333333;
    display: inline-block;
    margin:0 30px;
  }
  .date-infoicon {
    font-size: 32px;
    color: #999999;
    cursor: pointer;
    &:hover {
      color: #0871DB;
    }
  }
}
.date-tools {
  display: inline-block;
  margin-right: 0px;
  .tools-today {
    width: 54px;
    padding: 4px;
    display: inline-block;
    text-align: center;
    cursor: pointer;
    background: #FFFFFF;
    border: 1px solid #0871DB;
    border-radius: 4px;
  }
  .tools-switch {
    display: inline-block;
    margin-left: 20px;
  }
}
.unfinish {
  font-size: 14px;
  font-weight: bold;
  color: #666666;
}
.work-plan-contain {
  width: 100%;
  height: calc(100% - 50px);
  padding-top: 10px;
  overflow: hidden;
  .work-plan-right {
    width: 100% ;
    height: 100%;
    margin-left: 10px;
    display: inline-block;
    .work-plan-search {
      width: 100%;
      text-align: center;
    }
    .work-plan-contain {
      width: 100%;
      height: calc(100% - 28px);
      position: relative;
      .work-plan-item {
        position: absolute;
        height: 32px;
        line-height: 32px;
        width: calc(100% / 7);
        background-color: #10C8E6;
        margin-top: 37px;
        cursor: pointer;
      }
      table {
        width: 100%;
        height: 100%;
        text-align: center;
        border-collapse: separate;
        border-spacing: 0;
        border: 1px solid #E6E6E6;
        th {
          height: 32px;
          background-color: #F5F5F5 !important;
        }
        .active {
          color: #0871DB;
          background-color: #CEE1FF;
        }
        td {
          border-right: 1px solid #E6E6E6;
          border-top: 1px solid #E6E6E6;
          background-color: #FFFFFF;
        }
        td:last-child{
          border-right:none
        }
      }
    }
  }
}
</style>